package com.gaogis.platform.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.gaogis.platform.dto.*;
import javax.validation.Valid;
import org.springframework.web.bind.annotation.*;

import java.nio.file.Paths;
import java.util.Map;
import java.util.HashMap;
import org.springframework.beans.factory.annotation.Value;

import com.gaogis.platform.domain.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.io.File;
import java.io.FileReader;

import java.util.List;
import java.util.ArrayList;
import java.util.UUID;

import java.io.FileWriter;
import java.io.IOException;

import com.gaogis.platform.Response;
import lombok.extern.slf4j.Slf4j;


@RestController
@Slf4j
public class UserController{


	@Value("${db.dir}")
	private String dbDir;

	
	@GetMapping(value="/user")
	public String getUser(){
		return "ok";
	}

	public static String generateId() {
        	return UUID.randomUUID().toString().replace("-","");
    	}
	
	/**
 	 * 添加收藏
 	 */
	@PostMapping(value="/favorites/{uid}/add")
	public Object addFavorites(@PathVariable("uid") String uid,@Valid @RequestBody FavoriteDto dto){
		Map<String,Favorites> map = getFavorites();
		Favorites favorites=null;
		if(map.containsKey(uid)){
			favorites = map.get(uid);
		}else{
			favorites = new Favorites(uid);
			map.put(uid,favorites);
		}
                Favorite fav=new Favorite(generateId(),dto.date,dto.name,dto.lnglat,dto.zoom,dto.expression);
		fav.pid = getMaxPid(favorites);
		fav.description=dto.description;
		if(favorites.favorites==null){
			favorites.favorites=new ArrayList<Favorite>();
		}
		favorites.favorites.add(fav);
		List<Favorites> fs=new ArrayList<Favorites>();
		for(String key:map.keySet()){
			fs.add(map.get(key));
		}
		saveFavorites(fs);
		return Response.success(null);
	}

	private Integer getMaxPid(Favorites fs){
		int pid=0;
		if(fs.favorites!=null){
			for(Favorite f:fs.favorites){
				Integer i=f.pid;
				if(i!=null && i>pid){
					pid=i;
				}
			}
		}
		return pid+1;
	}

	private synchronized boolean saveFavorites(List<Favorites> list){
		String content=JSONObject.toJSONString(list);
		String path=dbDir+"/db.json";
		File f=new File(dbDir,"db.json");
		try{
			FileWriter writer = new FileWriter(f);
			writer.write(content);
			writer.flush();
			writer.close();
		}catch(IOException ioe){
			ioe.printStackTrace();
			return false;	
		}finally{
			
		}
		return true;
	}


        private synchronized boolean saveFavorites(Map<String,Favorites> map){
 
		List<Favorites> fs=new ArrayList<Favorites>();
                for(String key:map.keySet()){
                        fs.add(map.get(key));
                }
                return saveFavorites(fs);
        }

	private synchronized  Map<String,Favorites> getFavorites(){
	     //	String path=dbDir+"/db.json";
	        File folder=new File(dbDir);
		if(!folder.exists()){
			folder.mkdir();
		}
    	 	File file=new File(dbDir,"db.json");
		Map<String,Favorites> result=new HashMap<String,Favorites>();
		if(!file.exists()){
			return result;
		}
		try{
			FileReader fileReader = new FileReader(file);
			StringBuilder jsonContent = new StringBuilder();
		        int character;
        	    	while ((character = fileReader.read()) != -1) {
                		jsonContent.append((char) character);
	            	}
		        fileReader.close();	
			JSONArray jsonArray=JSON.parseArray(jsonContent.toString());
			if(jsonArray!=null){
				List<Favorites> favorites = JSON.parseArray(jsonArray.toJSONString(),Favorites.class);
				if(favorites!=null && favorites.size()>0){
					for(Favorites f:favorites){
						result.put(f.uid,f);
					}
				}
			}else{
				System.out.println("xxx");
			}
		}
		catch(Exception e)
		{
			System.out.println(e);
		}
		return result;
		
	}

	/**
	 * 删除收藏
	 */
	@PostMapping(value="/favorites/{uid}/delete/{favoriteid}")
	public Object deleteFavorites(@PathVariable("uid") String uid,@PathVariable("favoriteid") String favoriteid){
		Map<String,Favorites> map=getFavorites();
		if(!map.containsKey(uid)){
			return Response.fail("不存在");
		}
		Favorites fs= map.get(uid);
		if(fs.favorites==null){
			return Response.fail("不存在");
		}
		for(Favorite f:fs.favorites){
			if(f.id.equals(favoriteid)){
				fs.favorites.remove(f);
				saveFavorites(map);
				return Response.success(null);
				
				
			}
		}
		return Response.fail("不存在");
	}

	private Favorite getFavorite(String uid,String fid,Map<String,Favorites> fs){
		if(fs!=null)
		{
			if(fs.containsKey(uid)){
				Favorites fss=fs.get(uid);
				if(fss!=null){
					if(fss.favorites!=null){
						for(Favorite f:fss.favorites){
							if(f.id.equals(fid)){
								return f;
							}
						}
					}
				}
			}
		}
		return null;
	}

	/**
	 * 查询收藏
	 */
	@GetMapping(value="/favorites/list/{uid}")
	public Object listFavorites( @PathVariable("uid") String uid){
		Map<String,Favorites> list=getFavorites();
		if(list.containsKey(uid)){
			return Response.success(list.get(uid));
		}
		else{
			return Response.success(new Favorites(uid));
		}
	}

	@PostMapping(value="/favorites/{uid}/{favoriteid}")
	public Object modifyFavority(@PathVariable("uid") String uid,@PathVariable("favoriteid") String favoriteid,@Valid @RequestBody UpdateFavoriteDto dto){
		Map<String,Favorites> map=getFavorites();
		Favorite f=getFavorite(uid,favoriteid,map);
		if(f!=null){
			f.name=dto.name;
			f.description=dto.description;
			saveFavorites(map);
			return Response.success(null);
		}			
		return Response.fail("不存在");
	}


	
}
